<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="厨师姓名" prop="chefName">
              <el-input v-model="queryParams.chefName" placeholder="请输入厨师姓名" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['kitchen:chef:add']" type="primary" icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['kitchen:chef:remove']" type="danger" icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['kitchen:chef:export']" type="warning" icon="Download" @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="chefList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="厨师姓名" align="center" prop="chefName" />
        <el-table-column label="头像" align="center" prop="faceUrl" />
        <el-table-column label="手机号" align="center" prop="phoneNum" />
        <el-table-column label="身份证号" align="center" prop="idNo" />
        <el-table-column label="身份证状态" align="center" prop="idNoState">
          <template #default="scope">
            <dict-tag :options="check_state" :value="scope.row.idNoState"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="健康证状态" align="center" prop="healthCertificateState">
          <template #default="scope">
            <dict-tag :options="check_state" :value="scope.row.healthCertificateState"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="厨师等级" align="center" prop="chefLevel" />
        <el-table-column label="厨龄" align="center" prop="kitchenAge" />
        <el-table-column label="评分" align="center" prop="score" />
        <el-table-column label="服务费" align="center" prop="serviceFee" />
        <!--        <el-table-column label="服务费下包含的多少道加工费" align="center" prop="processingCount" />-->
        <el-table-column label="所在位置" align="center" prop="address" />
        <el-table-column label="格言" align="center" prop="maxim" />
        <el-table-column label="擅长的菜系" align="center" prop="majorCuisine" />
        <el-table-column label="职业履历" align="center" prop="careerPortfolio" />
        <!--        <el-table-column label="服务配备，多项逗号分隔" align="center" prop="serviceEquipment" />-->
        <el-table-column label="厨师状态" align="center" prop="state">
          <template #default="scope">
            <dict-tag :options="disable_state" :value="scope.row.state"></dict-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button v-hasPermi="['kitchen:chef:edit']" link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button v-hasPermi="['kitchen:chef:remove']" link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>


    <!-- 添加或修改厨师对话框 -->
    <el-drawer v-model="dialog.visible" size="70%" :title="dialog.title" :direction="direction" :before-close="cancel" close-on-click-modal>
      <el-form ref="chefFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="厨师姓名" prop="chefName">
              <el-input v-model="form.chefName" placeholder="请输入厨师姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="厨师等级" prop="chefLevel">
              <el-input v-model="form.chefLevel" placeholder="请输入厨师等级" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机号" prop="phoneNum">
              <el-input v-model="form.phoneNum" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证号" prop="idNo">
              <el-input v-model="form.idNo" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="厨龄" prop="kitchenAge">
              <el-input v-model="form.kitchenAge" placeholder="请输入厨龄">
                <template #append>年</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="评分" prop="score">
              <el-input v-model="form.score" placeholder="请输入评分" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="身份证审核" prop="idNoState">
              <!--              0 - 未审核 1 - 已通过 2 - 未通过-->
              <el-radio-group v-model="form.idNoState" placeholder="请选择分类状态">
                <el-radio v-for="dict in check_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="健康证审核" prop="healthCertificateState">
              <!--              0 - 未审核 1 - 已通过 2 - 未通过-->
              <el-radio-group v-model="form.idNoState" placeholder="请选择分类状态">
                <el-radio v-for="dict in check_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="厨师状态" prop="state">
              <el-radio-group v-model="form.state" placeholder="请选择分类状态">
                <el-radio v-for="dict in disable_state" :key="dict.value" :label="dict.label" :value="dict.value"></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="所属区划" prop="provinceArray">
              <AreaOptions ref="AreaOptions1" v-if="dialog.visible" :modelValue="form.provinceArray" :isHasDis="1"
                           @change="handleChangeProvince" @expand-change="handleExpandChange"></AreaOptions>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="服务费" prop="serviceFee" style="display: flex;">
              <el-input v-model="form.serviceFee" placeholder="请输入服务费" style="width:40%;">
                <template #append>元/单</template>
              </el-input>
              <el-input v-model="form.processingCount" placeholder="包含多少道加工费"  style="width:45%;">
                <template #prepend>包含</template>
                <template #append>道加工费</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <!--        <el-form-item label="经度" prop="lng">-->
            <!--          <el-input v-model="form.lng" placeholder="请输入经度" />-->
            <!--        </el-form-item>-->
            <!--        <el-form-item label="纬度" prop="lat">-->
            <!--          <el-input v-model="form.lat" placeholder="请输入纬度" />-->
            <!--        </el-form-item>-->
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" type="textarea" placeholder="请输入所在地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="格言" prop="maxim">
              <el-input v-model="form.maxim" type="textarea" placeholder="请输入格言" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="擅长的菜系" prop="majorCuisine">
              <el-input v-model="form.majorCuisine" type="textarea" placeholder="请输入擅长的菜系" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业履历" prop="careerPortfolio">
              <el-input v-model="form.careerPortfolio" type="textarea" placeholder="请输入职业履历" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务配备" prop="serviceEquipment">
              <el-input v-model="form.serviceEquipment" type="textarea" placeholder="请输入服务配备，多项逗号分隔" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="头像" prop="faceUrl">
              <ImagePreview :src="form.faceUrl"></ImagePreview>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="Chef" lang="ts">
import { listChef, getChef, delChef, addChef, updateChef } from '@/api/kitchen/chef';
import { ChefVO, ChefQuery, ChefForm } from '@/api/kitchen/chef/types';

import AreaOptions from '@/components/AreaOptions/index.vue';
import SinglePic from "@/components/SingleMaterial/index.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { module_state, check_state, disable_state } = toRefs<any>(proxy?.useDict('module_state','check_state', 'disable_state'));



const direction = ref<DrawerProps['direction']>('rtl');
const chefList = ref<ChefVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const chefFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ChefForm = {
  id: undefined,
  chefName: undefined,
  faceUrl: undefined,
  phoneNum: undefined,
  idNo: undefined,
  idNoState: undefined,
  healthCertificateState: undefined,
  chefLevel: undefined,
  kitchenAge: undefined,
  score: undefined,
  serviceFee: undefined,
  processingCount: undefined,
  lng: undefined,
  lat: undefined,
  address: undefined,
  maxim: undefined,
  majorCuisine: undefined,
  careerPortfolio: undefined,
  serviceEquipment: undefined,
  state: undefined,
  createTime: undefined,
  provinceArray: undefined
};
const data = reactive<PageData<ChefForm, ChefQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    chefName: undefined,
    faceUrl: undefined,
    phoneNum: undefined,
    idNo: undefined,
    idNoState: undefined,
    healthCertificateState: undefined,
    chefLevel: undefined,
    kitchenAge: undefined,
    score: undefined,
    serviceFee: undefined,
    processingCount: undefined,
    lng: undefined,
    lat: undefined,
    address: undefined,
    maxim: undefined,
    majorCuisine: undefined,
    careerPortfolio: undefined,
    serviceEquipment: undefined,
    state: undefined,
    createTime: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    chefName: [{ required: true, message: '厨师姓名不能为空', trigger: 'blur' }],
    faceUrl: [{ required: true, message: '头像不能为空', trigger: 'blur' }],
    phoneNum: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
    idNo: [{ required: true, message: '身份证号不能为空', trigger: 'blur' }],
    idNoState: [{ required: true, message: '身份证审核状态 0 - 未审核 1 - 已通过 2 - 未通过不能为空', trigger: 'blur' }],
    healthCertificateState: [{ required: true, message: '健康证审核状态 0 - 未审核 1 - 已通过 2 - 未通过不能为空', trigger: 'blur' }],
    chefLevel: [{ required: true, message: '厨师等级不能为空', trigger: 'blur' }],
    kitchenAge: [{ required: true, message: '厨龄不能为空', trigger: 'blur' }],
    score: [{ required: true, message: '评分不能为空', trigger: 'blur' }],
    serviceFee: [{ required: true, message: '服务费不能为空', trigger: 'blur' }],
    processingCount: [{ required: true, message: '服务费下包含的多少道加工费不能为空', trigger: 'blur' }],
    lng: [{ required: true, message: '经度不能为空', trigger: 'blur' }],
    lat: [{ required: true, message: '纬度不能为空', trigger: 'blur' }],
    address: [{ required: true, message: '所在位置不能为空', trigger: 'blur' }],
    maxim: [{ required: true, message: '格言不能为空', trigger: 'blur' }],
    majorCuisine: [{ required: true, message: '擅长的菜系不能为空', trigger: 'blur' }],
    careerPortfolio: [{ required: true, message: '职业履历不能为空', trigger: 'blur' }],
    serviceEquipment: [{ required: true, message: '服务配备，多项逗号分隔不能为空', trigger: 'blur' }],
    state: [{ required: true, message: '厨师状态  0 - 不能为空', trigger: 'blur' }],
    createTime: [{ required: true, message: '添加时间不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询厨师列表 */
const getList = async () => {
  loading.value = true;
  const res = await listChef(queryParams.value);
  chefList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

const handleChangeProvince = (e) => {
  console.log('handleChangeProvince',e);
  form.value.provinceArray = e;
};

// TODO：各父级选项值组成的数组
const handleExpandChange = (e) => {
  console.log(e);
};


/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  chefFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ChefVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加厨师';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ChefVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getChef(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改厨师';
};

/** 提交按钮 */
const submitForm = () => {
  chefFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateChef(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addChef(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ChefVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除厨师编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delChef(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'kitchen/chef/export',
    {
      ...queryParams.value
    },
    `chef_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
